<template>
  <div class="app-container">
    <el-card>

      <el-row :gutter="20">

        <el-col :span="7">
          <div class="filter-container">
            <el-card>
              <el-form ref="searchform" :inline="true" :model="searchform" class="demo-form-inline" size="small">
                <el-form-item label="用户信息">
                  <el-input v-model="searchform.keywords" clearable placeholder="用户信息" />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="handleSearch()">查询</el-button>
                </el-form-item>
              </el-form>
            </el-card>
          </div>
          <div class="grid-content bg-purple">
            <div class="grid-content bg-purple">
              <el-table
                :data="tableDataItemss"
                style="width: 100%;margin-bottom: 20px;"
                row-key="Id"
                border
                size="mini"
                max-height="850"
                default-expand-all
                highlight-current-row
                :tree-props="{children: 'Children'}"
                @row-click="handleClickItemsChange"
              >
                <el-table-column
                  prop="NickName"
                  label="昵称"
                />
                <el-table-column
                  label="等级"
                  prop="MemberGradeName"
                  align="center"
                />
              </el-table>
            </div>
          </div>
        </el-col>
        <el-col :span="17">
          <div class="grid-content bg-purple">
            <div class="list-btn-container">
              <el-form ref="searchform" :inline="true" :model="searchform" class="demo-form-inline" size="small">
                <el-form-item>
                  <el-button-group>
                    <el-button type="default" icon="el-icon-refresh" size="mini" @click="loadItemsDetailTableData()">重置</el-button>
                    <slot v-for="itemf in loadItemsDetailBtnFunc">
                      <el-button v-if="itemf.FullName==='添加空降代理'" type="primary" icon="el-icon-plus" size="mini" @click="ShowItemsDetailEditOrViewDialog()">添加空降代理</el-button>
                    </slot>
                  </el-button-group>
                </el-form-item>
              </el-form>
            </div>
          </div>
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>团队成员</span>
            </div>
            <el-table
              ref="gridtable"
              v-loading="tableloading"
              :data="tableData"
              border
              stripe
              highlight-current-row
              style="width: 100%"
              :default-sort="{prop: 'SortCode', order: 'descending'}"
              @select="handleSelectChange"
              @select-all="handleSelectAllChange"
              @sort-change="handleSortChange"
            >
              <el-table-column
                type="selection"
                width="30"
              />
              <el-table-column
                prop="NickName"
                label="昵称"
                width="180"
              />
              <el-table-column
                prop="RealName"
                label="姓名"
                width="180"
              />
              <el-table-column
                prop="MemberGradeName"
                label="等级"
                width="280"
                align="center"
              />
              <el-table-column
                prop="ReferralUserName"
                label="上级分销员"
                width="280"
                align="center"
              />
              <el-table-column
                prop="ParentUserName"
                label="上级姓名"
                width="280"
                align="center"
              />
              <el-table-column
                label="状态"
                sortable="custom"
                width="80"
                prop="IsPay"
                align="center"
              >
                <template slot-scope="scope">
                  <el-tag
                    :type="scope.row.EnabledMark === true ? 'success' : 'info'"
                    disable-transitions
                  >{{ scope.row.IsPay===true?'已支付':'未支付' }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column
                prop="CreatorTime"
                label="加入时间"
                width="180"
                sortable
              />
              <!-- <el-table-column
                fixed="right"
                label="操作"
              >
                <template slot-scope="scope">
                  <el-button type="text" size="small" @click="ShowEditOrViewDialog('select',scope.row)">编辑</el-button>
                </template> -->
              </el-table-column>
            </el-table>
          </el-card>
          <div class="pagination-container">
            <el-pagination
              background
              :current-page="pagination.currentPage"
              :page-sizes="[5,10,20,50,100, 200, 300, 400]"
              :page-size="pagination.pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="pagination.pageTotal"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-col>
      </el-row>
    </el-card>
    <el-dialog ref="dialogEditForm" :title="editFormTitle" :visible.sync="dialogEditFormVisible" width="660px">
      <el-form ref="editFrom" :inline="true" :model="editFrom" :rules="rules" class="demo-form-inline">
        <el-form-item label="等级" :label-width="formLabelWidth" prop="MemberGradeId">
          <el-select v-model="editFrom.MemberGradeId" clearable placeholder="请选择等级" style="width:500px;">
            <el-option
              v-for="item in selectLeves"
              :key="item.Id"
              :label="item.Name"
              :value="item.Id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="上级" :label-width="formLabelWidth" prop="ParentUserId">
          <el-select
            v-model="editFrom.ParentUserId"
            style="width:500px"
            placeholder="请选择上级"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogEditFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEditForm()">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog ref="dialogEditItemsDetailForm" :title="editItemsDetailFormTitle+'空降代理'" :visible.sync="dialogItemsDetailEditFormVisible" width="660px">
      <el-form ref="editItemsDetailFrom" :model="editItemsDetailFrom" :rules="rulesfun">
        <el-form-item label="用户" :label-width="formLabelWidth" prop="UserId">
          <el-select
            v-model="editItemsDetailFrom.UserId"
            style="width:500px"
            filterable
            placeholder="请选择用户"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item></el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogItemsDetailEditFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEditItemsDetailForm()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getPage, GetAllParent, GetUserDetail, save } from '@/api/shop/invitationlogservice'
import { GetAllUsersEnable } from '@/api/security/userservice'
import { GetAllEnable } from '@/api/shop/membergrade'
import { getListMeunFuntionBymeunCode } from '@/api/basebasic'

export default {
  data() {
    return {
      searchform: {
        keywords: '',
        code: ''
      },
      selectSystemType: [],
      loadItemsBtnFunc: [],
      loadItemsDetailBtnFunc: [],
      tableData: [],
      editFormTitle: '',
      selectLeves: [],
      tableloading: false,
      pagination: {
        currentPage: 1,
        pagesize: 10,
        pageTotal: 0
      },
      sortableData: {
        order: '',
        sort: ''
      },
      loading: false,
      selectItemsId: '',
      options: [],
      list: [],
      dialogItemsEditFormVisible: false,
      editItemsFormTitle: '',
      selectedItemsOptions: [],
      selectItemss: [],
      formLabelWidth: '80px',
      currentItemsId: '',
      dialogItemsDetailEditFormVisible: false,
      editItemsDetailFormTitle: '',
      selectedItemsDetailOptions: [],
      selectItemsDetails: [],
      editItemsDetailFrom: { UserId: '' },
      dialogEditFormVisible: false,
      editFrom: {
        ParentUserId: '',
        MemberGradeId: ''
      },
      currentId: '', // 当前操作对象的ID值，主要用于修改
      currentSelected: [],
      tableDataItemss: [],
      rules: {
        ParentUserId: [
          { required: true, message: '请选择上级', trigger: 'blur' }
        ],
        MemberGradeId: [
          { required: true, message: '请选择等级', trigger: 'blur' }
        ]
      },
      rulesfun:
      {
        UserId: [
          { required: true, message: '请选择用户', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.pagination.currentPage = 1
    GetAllEnable().then(res => {
      this.selectLeves = res.ResData
    })

    this.InitDictItem()
    this.loadTableData()
    this.loadTablePageData()
    this.loadItemsBtnFunc = JSON.parse(localStorage.getItem('yueboncurrentfuns'))
  },
  mounted() {
    GetAllUsersEnable().then(res => {
      this.options = res.ResData.map(item => {
        return { value: `${item.Id}`, label: `${item.NickName}` }
      })
    })
  },
  methods: {
    /**
     * 初始化数据
     */
    InitDictItem() {
      getListMeunFuntionBymeunCode('invitationlog_view').then(res => {
        this.loadItemsDetailBtnFunc = res.ResData
      })
    },
    remoteMethod(query) {
      if (query !== '') {
        this.loading = true
        setTimeout(() => {
          this.loading = false
          this.options = this.list.filter(item => {
            return item.label.toLowerCase()
              .indexOf(query.toLowerCase()) > -1
          })
        }, 200)
      } else {
        this.options = []
      }
    },
    /**
     * 加载页面左侧菜单table数据
     */
    loadTableData: function() {
      GetAllParent(this.searchform.keywords).then(res => {
        this.selectItemss = this.tableDataItemss = res.ResData
      })
      this.loadTablePageData()
    },
    /**
     * 点击查询菜单
     */
    handleSearch: function() {
      this.loadTableData()
    },
    ShowItemsDetailEditOrViewDialog: function(view) {
      this.editItemsDetailFormTitle = '新增'
      this.currentId = ''
      this.dialogItemsDetailEditFormVisible = true
      this.$refs['editItemsDetailFrom'].resetFields()
    },
    /**
     * 点击查询
     */
    handleSearchItemsDetail: function() {
      this.pagination.currentPage = 1
      this.loadItemsDetailTableData()
    },
    /**
     * 加载页面table数据
     */
    loadTablePageData: function() {
      this.tableloading = true
      var seachdata = {
        'currenetPageIndex': this.pagination.currentPage,
        'pageSize': this.pagination.pagesize,
        'parentUserId': this.currentItemsId
      }
      getPage(seachdata).then(res => {
        this.tableData = res.ResData.Items
        this.pagination.pageTotal = res.ResData.TotalItems
        this.tableloading = false
      })
    },

    /**
     * 添加添加分类是选择父级分类
     */
    handleItemsChange: function() {
      console.log(this.selectedItemsOptions)
      if (this.currentItemsId === this.selectedItemsOptions) {
        this.$alert('不能选择自己作为父级', '提示')
        this.selectedItemsOptions = ''
        return
      }
      this.editItemsFrom.ParentId = this.selectedItemsOptions
    },
    /**
     * 添加分类值是选择分类
     */
    handleAddItemsDetailChange: function() {
      console.log(this.selectedItemsOptions)
      this.selectItemsId = this.selectedItemsOptions
      this.loadItemsDetailTree()
      this.editItemsDetailFrom.ItemId = this.selectedItemsOptions
    },
    ShowEditOrViewDialog: function(view, row) {
      this.currentId = row.Id
      this.editFormTitle = '编辑'
      this.dialogEditFormVisible = true
      this.bindEditInfo(row.Id)
    },
    bindEditInfo: function(userid) {
      GetUserDetail(userid).then(res => {
        this.editFrom.ParentUserId = res.ResData.ParentUserId
        this.editFrom.MemberGradeId = res.ResData.MemberGradeId
      })
    },
    saveEditItemsDetailForm() {
      this.$refs['editItemsDetailFrom'].validate((valid) => {
        if (valid) {
          const data = {
            'userid': this.editItemsDetailFrom.UserId
          }

          var url = 'InvitationLog/AddAirborne'
          if (this.currentId !== '') {
            // url = 'ItemsDetail/Update?id=' + this.currentId
          }
          save(data, url).then(res => {
            if (res.Success) {
              this.$message({
                message: '恭喜你，操作成功',
                type: 'success'
              })
              this.dialogItemsDetailEditFormVisible = false
              this.editItemsDetailFrom.UserId = ''

              this.$nextTick(function() {
                this.$refs['editItemsDetailFrom'].resetFields()
              })
              this.loadItemsDetailTableData()
              this.InitDictItem()
              this.loadTableData()
            } else {
              this.$message({
                message: res.ErrMsg,
                type: 'error'
              })
            }
          })
        } else {
          return false
        }
      })
    },
    saveEditForm() {
      console.log(this.editFrom.RoleId)
      this.$refs['editFrom'].validate((valid) => {
        if (valid) {
          const data = {
            MemberGradeId: this.editFrom.MemberGradeId,
            ParentUserId: this.editFrom.ParentUserId,
            'Id': this.currentId
          }
          var url = 'InvitationLog/Insert'
          if (this.currentId !== '') {
            url = 'InvitationLog/UpdateFieId'
          }
          save(data, url).then(res => {
            if (res.Success) {
              this.$message({
                message: '恭喜你，操作成功',
                type: 'success'
              })
              this.dialogEditFormVisible = false
              this.currentSelected = ''
              this.selectedOrganizeOptions = ''
              this.$refs['editFrom'].resetFields()
              this.loadTableData()
              this.InitDictItem()
            } else {
              this.$message({
                message: res.ErrMsg,
                type: 'error'
              })
            }
          })
        } else {
          return false
        }
      })
    },
    /**
     * 当表格的排序条件发生变化的时候会触发该事件
     */
    handleSortChange: function(column) {
      this.sortableData.sort = column.prop
      if (column.order === 'ascending') {
        this.sortableData.order = 'asc'
      } else {
        this.sortableData.order = 'desc'
      }
      this.loadItemsDetailTableData()
    },
    //
    handleClickItemsChange: function(row, column, event) {
      this.searchform.code = row.EnCode
      this.currentItemsId = row.Id
      this.pagination.currentPage = 1
      this.loadTablePageData()
    },
    /**
     * 当用户手动勾选checkbox数据行事件
     */
    handleSelectChange: function(selection, row) {
      this.currentSelected = selection
    },
    /**
     * 当用户手动勾选全选checkbox事件
     */
    handleSelectAllChange: function(selection) {
      this.currentSelected = selection
    },

    /**
     * 加载页面table数据
     */
    loadItemsDetailTableData: function() {
      this.tableloading = true
      var seachdata = {
        'currenetPageIndex': this.pagination.currentPage,
        'pageSize': this.pagination.pagesize
      }
      getPage(seachdata).then(res => {
        this.tableData = res.ResData.Items
        this.pagination.pageTotal = res.ResData.TotalItems
        this.tableloading = false
      })
    },
    /**
     * 选择每页显示数量
     */
    handleSizeChange(val) {
      this.pagination.pagesize = val
      this.pagination.currentPage = 1
      this.loadTableData()
      this.loadTablePageData()
    },
    /**
     * 选择当页面
     */
    handleCurrentChange(val) {
      this.pagination.currentPage = val
      this.loadTablePageData()
    }

  }
}
</script>
<style>
.el-cascader{
  width: 100%;
}
</style>
